/**
 * https://leetcode.cn/problems/take-k-of-each-character-from-left-and-right/submissions/568555688/?envType=daily-question&envId=2024-09-27
 */

class Solution {
public:
    int takeCharacters(string s, int k) {
        if(k==0)
        return 0;
        int lword[3]={0};
        int rword[3]={0};
        int n=s.length();
        int lsum=0;
        int l=0;
        for(;l<n;++l){
            lword[s[l]-97]++;
            if(lword[s[l]-97]==k)
            lsum++;
            if(lsum==3)
            break;
        }
        int rsum=0;
        int r=n-1;
        for(;r>=0;--r){
            rword[s[r]-97]++;
            if(rword[s[r]-97]==k)
            rsum++;
            if(rsum==3)
            break;
        }
        if(lsum!=3&&rsum!=3)
        return -1;
        int m=min(l+1,n-r);
        cout<<l<<endl;
        cout<<r<<endl;
        if(l+1>n-r){
            l=0;
            for(;r<n;){
                int t=s[r]-97;
                rword[t]--;
                r++;
                while(l<n&&rword[t]!=k){
                    rword[s[l]-97]++;
                    l++;
                }
                while(r<n&&rword[s[r]-97]>k){
                    rword[s[r]-97]--;
                    r++;
                }
                cout<<"l="<<l<<endl;
                cout<<"r="<<r<<endl;
                cout<<m<<endl;
                m=min((n-r+l),m);
            }
        }
        else{
            r=n-1;
            cout<<"l="<<l<<endl;
            cout<<"r="<<r<<endl;
            for(;l>=0;){
                int t=s[l]-97;
                lword[t]--;
                l--;
                while(r>=0&&lword[t]!=k){
                    lword[s[r]-97]++;
                    r--;
                }
                while(l>=0&&lword[s[l]-97]>k){
                    lword[s[l]-97]--;
                    l--;
                }
                cout<<"l="<<l<<endl;
                cout<<"r="<<r<<endl;
                cout<<m<<endl;
                m=min((n-r+l),m);
            }
            }
            return m;
    }
};